package edu.neu.javaweb.controller;

import edu.neu.javaweb.service.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String username = request.getParameter("username");
        String passwd = request.getParameter("passwd");
        log.info(username);
        log.info(passwd);

        HttpSession session = request.getSession();




        UserService loginService = new UserService();
        if (loginService.login(username, passwd)) {
            //ok
            request.getSession().setAttribute("isLogin", true);
            request.getSession().setAttribute("username", username);
            request.getSession().setAttribute("passwd", passwd);
            response.sendRedirect("pages/welcome.html");
//            request.getRequestDispatcher("/emp").forward(request, response);
        } else {
            //fail
            request.getSession().setAttribute("isLogin", false);
//            response.getWriter().print("<html><body><h3><font color = 'red'>Login fail! Login Again!</font></h3></body></html>");
            response.sendRedirect("login.html?fail=true");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }
}
